package com.matrix.async.action;

import com.google.gson.Gson;
import com.matrix.async.VO.AsyncTaskVo;
import com.matrix.async.bean.AsyncTaskBean;
import com.matrix.async.core.Tools;
import com.matrix.async.dao.AsyncTaskDao;
import com.matrix.async.service.AsyncTaskService;
import com.matrix.core.pojo.AjaxResult;
import com.matrix.core.pojo.PaginationVO;
import com.matrix.core.web.BaseAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "developer/async")
public class AsyncTaskAction extends BaseAction {

	@Autowired
	private AsyncTaskService asyncTaskService;

	@Autowired
	private AsyncTaskDao asyncTaskDao;


	/**
	 * 新增定时任务
	 *
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date Dec 10, 2017
	 * @return
	 */
	@RequestMapping(value = "/addTask")
	public @ResponseBody AjaxResult addTask(AsyncTaskVo asyncTaskVo) {
		Gson gson = new Gson();
		Map maps = gson.fromJson(asyncTaskVo.getDataMap(),Map.class);
		asyncTaskService.createTask(Tools.getHostName(), asyncTaskVo.getTaskType(), maps);
		return new AjaxResult(AjaxResult.STATUS_SUCCESS, "新增成功");
	}



	@RequestMapping(value = "/del/{taskId}/{packageId}")
	public @ResponseBody AjaxResult del(@PathVariable("taskId") String taskId,
			@PathVariable("packageId") String packageId) {
		asyncTaskDao.deleteTaskById(taskId);
		asyncTaskDao.deleteTaskPackageById(packageId);
		asyncTaskDao.deleteTaskDateByTaskId(taskId);
		return new AjaxResult(AjaxResult.STATUS_SUCCESS, "删除成功");
	}

	@RequestMapping(value = "/copy/{taskId}")
	public @ResponseBody AjaxResult copy(@PathVariable("taskId") String taskId) {
		AsyncTaskBean task = asyncTaskDao.selectTaskByTaskId(taskId);
		asyncTaskService.createTask(Tools.getHostName(), task.getTaskType(), asyncTaskService.getTaskDataList(taskId));
		return new AjaxResult(AjaxResult.STATUS_SUCCESS, "复制成功");
	}

	/**
	 * 查询运行中的异步任务
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody AjaxResult showList(AsyncTaskBean task, PaginationVO pageVo) {

		List<AsyncTaskBean> dataList = asyncTaskService.findInPage(task, pageVo);
		AjaxResult result = new AjaxResult(AjaxResult.STATUS_SUCCESS, dataList, asyncTaskService.findTotal(task));
		return result;
	}

}